/* eslint-disable */
import { fileURLToPath, URL } from 'node:url'
import { mergeConfig, defineConfig, configDefaults } from 'vitest/config'
import { UserConfig, ConfigEnv, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

import viteCompression from 'vite-plugin-compression'
import { visualizer } from 'rollup-plugin-visualizer'

//element-plus 组件
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

/* eslint-disable no-new */
export default ({ mode }: ConfigEnv): UserConfig => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  // 设置第三个参数为 '' 来加载所有环境变量，而不管是否有 `VITE_` 前缀。
  //const env = loadEnv(mode, process.cwd(), '') || {}
  const env = loadEnv(mode, process.cwd())
  // 你应该能看到你的环境变量值
  // https://vitejs.dev/config/
  return defineConfig({
    // 项目根路径
    root: './',
    // 应用的基础路径（例如部署到子目录时设置为'/app/'）
    base: env.VITE_BASE_URL,
    server: {
      host: '0.0.0.0', // 设置服务器监听的主机名或 IP 地址，默认为localhost
      port: Number(env.VITE_APP_PORT), // 设置服务器端口号
      open: true, // 自动打开浏览器
      cors: true, // 启用跨域支持
      hmr: { overlay: false }, // 关闭热更新错误提示
      proxy: {
        // '/api': {
        //   target: `${env.VITE_APP_REQUSET_URL}`,
        //   changeOrigin: true,
        //   rewrite: (path) => path.replace(/^\/api/, '')
        // }
        [env.VITE_APP_BASE_API]: {
          target: `${env.VITE_APP_REQUSET_URL}`, // 后端服务实际地址
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(new RegExp('^' + env.VITE_APP_BASE_API), '')
        }
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      //开启gzip
      viteCompression({
        //生成压缩包gz
        verbose: true,
        disable: false,
        threshold: 1024000 / 2, // 对大于 1mb 的文件进行压缩
        algorithm: 'gzip',
        ext: '.gz'
      }),
      visualizer({
        emitFile: false,
        filename: 'public/stats.html',
        open: true,
        sourcemap: true
      }),
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()]
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@assets': fileURLToPath(new URL('./src/assets', import.meta.url)),
        '@components': fileURLToPath(new URL('./src/components', import.meta.url)),
        '@images': fileURLToPath(new URL('./src/images', import.meta.url)),
        '@store': fileURLToPath(new URL('./src/store', import.meta.url)),
        '@views': fileURLToPath(new URL('./src/views', import.meta.url)),
        '@api': fileURLToPath(new URL('./src/api', import.meta.url))
      }
    },
    build: {
      // 输出目录
      outDir: `dist/${env.VITE_APP_PACKAGE_NAME}`,
      // 是否在输出目录保留源码映射文件
      sourcemap: true,
      // 静态资产处理
      assetsDir: 'assets',
      // 压缩选项
      minify: 'terser', // 或者指定自定义压缩插件-需要npm install terser@* -D
      // 打包分包
      rollupOptions: {
        output: {
          /** S-静态文件按类型分包 */
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]',
          /** E-静态文件按类型分包 */
          manualChunks(id) {
            // 超大静态资源拆分
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString()
            }
          }
        }
      },
      terserOptions: {
        //打包后移除console和注释
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      }
    },
    //CSS样式配置
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true
        }
      },
      postcss: {
        plugins: [
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: (atRule) => {
                if (atRule.name === 'charset') {
                  atRule.remove()
                }
              }
            }
          }
        ]
      }
    },
    // 预编译
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'pinia',
        'axios',
        '@vueuse/core',
        'path-to-regexp',
        'echarts',
        '@wangeditor/editor',
        '@wangeditor/editor-for-vue',
        'vue-i18n',
        '@vueup/vue-quill',
        '@iconify/iconify',
        'element-plus/es/components/form/style/css',
        'element-plus/es/components/form-item/style/css',
        'element-plus/es/components/button/style/css',
        'element-plus/es/components/input/style/css',
        'element-plus/es/components/input-number/style/css',
        'element-plus/es/components/switch/style/css',
        'element-plus/es/components/upload/style/css',
        'element-plus/es/components/menu/style/css',
        'element-plus/es/components/col/style/css',
        'element-plus/es/components/icon/style/css',
        'element-plus/es/components/row/style/css',
        'element-plus/es/components/tag/style/css',
        'element-plus/es/components/dialog/style/css',
        'element-plus/es/components/loading/style/css',
        'element-plus/es/components/radio/style/css',
        'element-plus/es/components/radio-group/style/css',
        'element-plus/es/components/popover/style/css',
        'element-plus/es/components/scrollbar/style/css',
        'element-plus/es/components/tooltip/style/css',
        'element-plus/es/components/dropdown/style/css',
        'element-plus/es/components/dropdown-menu/style/css',
        'element-plus/es/components/dropdown-item/style/css',
        'element-plus/es/components/sub-menu/style/css',
        'element-plus/es/components/menu-item/style/css',
        'element-plus/es/components/divider/style/css',
        'element-plus/es/components/card/style/css',
        'element-plus/es/components/link/style/css',
        'element-plus/es/components/breadcrumb/style/css',
        'element-plus/es/components/breadcrumb-item/style/css',
        'element-plus/es/components/table/style/css',
        'element-plus/es/components/tree-select/style/css',
        'element-plus/es/components/table-column/style/css',
        'element-plus/es/components/select/style/css',
        'element-plus/es/components/option/style/css',
        'element-plus/es/components/pagination/style/css',
        'element-plus/es/components/tree/style/css',
        'element-plus/es/components/alert/style/css',
        'element-plus/es/components/checkbox/style/css',
        'element-plus/es/components/date-picker/style/css',
        'element-plus/es/components/transfer/style/css',
        'element-plus/es/components/tabs/style/css',
        'element-plus/es/components/image/style/css',
        'element-plus/es/components/tab-pane/style/css'
      ]
    },
    test: {
      environment: 'jsdom',
      exclude: [...configDefaults.exclude, 'e2e/**'],
      root: fileURLToPath(new URL('./', import.meta.url))
    }
  })
}
